package com.yuyue.springFramework.note03.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Cglib代理优化，实现拦截器类
 */
public class CostCglib2 implements MethodInterceptor {

    //重写拦截器方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long startTime = System.nanoTime();

        //调用原方法并获取返回值
        Object result = methodProxy.invokeSuper(o,objects);

        long endTime = System.nanoTime();
        System.out.println(method.getName() + "耗时（纳秒）：" + (endTime - startTime));

        return result;
    }

    public static <T> T createProxy(T target){
        //创建增强类
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setCallback(new CostCglib2());
        //设置拦截器
        enhancer.setSuperclass(target.getClass());

        //返回代理类
        return (T)enhancer.create();
    }
}
